const { default: request } = require("../../plugins/request")
const { default: store } = require("../../utils/store")
const { getLocation } = require("../../utils/utils")
import { valIsNull } from "../../utils/utils"

const pageOptions = {
	// 页面数据
	data: {
		isFirstOnShow: true, // 是否为首次执行onShow
		auditStatus: "", // 审核状态，auditing: 审核中，pass: 审核通过，reject: 审核拒绝
		userInfo: {
			xm: "", //姓名
			xb: "", //性别
			mz: "", //民族
			cc: "", //学历
			xh: "", //学号
			ksh: "", // 考生号
			nj: "", //年级
			bjmc: "", //班级名称
			xymc: "", //学院名称
			zymc: "", //专业名称
		}, // 用户信息
		needHandleSignature: false, // 是否需要手写签名
		signatureBase64Row: "", // 签名图片base64 Row 用于提交
		signatureBase64: "", // 签名图片base64
		recordId: "", // 记录id（用于提交签名）
		checkDate: "", // 核验时间
		rejectReason: "", // 拒绝原因
		limitState: false, //限制状态，false不限制，true限制
		shsj: "", //审核时间
		maxRetryCount: -1, //最大重试次数
		openType: "", //打开方式，1：从首页打开，2：从核验记录打开
	},
	// 页面载入时
	onLoad(e) {
		if (e.openType) {
			this.setData({
				openType: e.openType,
			})
		} else {
			this.setData({
				openType: "",
			})
		}
		this.init(e)
	},
	// 页面初始化
	init(e) {
		let data = {}
		data = {
			auditStatus: e.auditStatus,
			//获取用户信息
			userInfo: store.userInfo.get(),
			recordId: e.recordId,
			rejectReason: e.rejectReason,
			maxRetryCount: e.maxRetryCount,
		}
		if (valIsNull(e.recordId) && this.data.openType === "1") {
			this.queryResult()
		} else {
			data.needHandleSignature = store.needHandleSignature.get()
		}
		this.setData(data)
	},
	// 页面准备好时
	onReady() {},
	// 页面显示时
	onShow() {
		this.setData({
			limitState: store.limitState.get(),
		})
		// const maxRetryCount = store.maxRetryCount.get()
		// if (maxRetryCount !== null) {
		// 	this.setData({
		// 		maxRetryCount: maxRetryCount,
		// 	})
		// }
	},
	// 页面隐藏时
	onHide() {},
	// 页面卸载时
	onUnload() {},
	// 下拉页面时
	onPullDownRefresh() {},
	// 到达页面底部时
	onReachBottom() {},
	// 页面滚动时
	onPageScroll() {},
	// 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
	onShareAppMessage() {
		/* const title = ''
    const path = ''
    const imageUrl = ``

    return {
      title,
      path,
      imageUrl,
    } */
	},
	valIsNull,
	//查询记录id
	queryResult() {
		wx.showLoading({
			title: "加载中",
		})
		request({
			url: "api/wx/xshy/get-verified-result",
			method: "post",
		})
			.then((data) => {
				wx.hideLoading()
				if (!valIsNull(data)) {
					this.setData({
						recordId: data.recordId,
						checkDate: data.yzsj,
					})
					if (data.zzjg === 3 || data.zzjg === 4) {
						this.setData({
							rejectReason: data.reviewDescription,
							shsj: data.shsj,
						})
					} else if (data.detail) {
						const detail = JSON.parse(data.detail)
						let reason = ""
						for (const item of detail) {
							reason += item.remark + "；"
						}
						this.setData({
							rejectReason: reason,
						})
					}
					if (!valIsNull(data.handSignImg)) {
						this.setData({
							needHandleSignature: false,
						})
					} else {
						this.setData({
							needHandleSignature: true,
						})
					}
				}
			})
			.catch((err) => {
				wx.hideLoading()
				wx.showToast({
					title: err,
					icon: "none",
				})
				console.log(err, "err")
			})
	},
	// 打开签名面板
	handleShowSignature() {
		const instance = this.selectComponent("#signature")
		instance.showCanvas()
	},
	// 关闭签名面板
	handleSignatureSubmit(e) {
		const base64 = e.detail
		const base64Row = base64.split(",")[1]
		this.setData({
			signatureBase64Row: base64Row,
			signatureBase64: base64,
		})
	},
	//提交签名
	async submitSignature() {
		//检查是否有签名
		if (valIsNull(this.data.signatureBase64)) {
			wx.showToast({
				title: "请先签名",
				icon: "none",
			})
			return
		}
		//查看先前是否已经获取过位置了
		let location = store.location.get()
		if (valIsNull(location)) {
			//发起定位
			const res = await getLocation()
			location = JSON.stringify(res.location)
		}
		//提交签名
		wx.showLoading({
			title: "加载中",
		})
		request({
			url: "api/wx/xshy/upload-signature-img",
			method: "post",
			data: {
				recordId: this.data.recordId,
				signature: this.data.signatureBase64Row,
				location: location,
			},
		})
			.then((res) => {
				wx.hideLoading()
				wx.showToast({
					title: "提交成功",
					icon: "none",
				})
				this.setData({
					needHandleSignature: false,
				})
				store.needHandleSignature.set(false)
			})
			.catch((err) => {
				wx.hideLoading()
				wx.showToast({
					title: err,
					icon: "none",
				})
				console.log(err, "err")
			})
	},
	//回到首页
	goBackToHomePage() {
		wx.redirectTo({
			url: "/informationVerification/pages/index/index",
		})
	},
	//重新核验
	reCheck() {
		//清空之前的核验缓存
		store.sfz_back.set("")
		store.sfz_front.set("")
		store.face.set("")
		// store.location.set("")
		store.faceImageId.set("")

		//判断是否需要上传位置
		if (
			valIsNull(store.location.get()) &&
			(store.needLocation.get() ||
				(store.locationLimit.get() && store.locationLimit.get().limit))
		) {
			wx.navigateTo({
				url: "/informationVerification/pages/getLocation/index",
			})
			return
		}
		//判断是否需要上传身份证照片
		if (store.needSfzImageUpload.get()) {
			wx.navigateTo({
				url: "/informationVerification/pages/uploadIdCard/index",
			})
			return
		}
		//跳转到人像拍照页面
		wx.navigateTo({
			url: "/informationVerification/pages/photoInstructions/index",
		})
	},
}

Page(pageOptions)
